﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using IfSoft.OA.Entities;

namespace IfSoft.OA.DataAccess
{
    public class UserRepository : RepositoryBase, IUserRepository
    {
        #region Basic CRUD operations

        public void Create(User bo)
        {
            using (var context = GetContext())
            {
                context.Users.Add(bo);
                context.SaveChanges();
            }
        }
      
        public void Update(User bo)
        {
            using (var context = GetContext())
            {
                var update = context.Users.FirstOrDefault(e => e.Id == bo.Id);
                context.Entry(update).State = EntityState.Modified;
                context.SaveChanges();
            }
        }

        public void Delete(int id)
        {
            using (var context = GetContext())
            {
                var delete = context.Users.Find(id);
                context.Users.Remove(delete);
                context.SaveChanges();
            }
        }

        public User SearchById(int id)
        {
            using (var context = GetContext())
            {
                return context.Users.Find(id);
            }
        }

        public List<User> Search(UserCriteria criteria)
        {
            using (var context = GetContext())
            {
                return context.Users.ToList();
            }
        }

        public PagedList<User> SearchPagedList(UserCriteria criteria)
        {
            using (var context = GetContext())
            {
                return new PagedList<User>(context.Users.SortBy("Id", true), criteria.StartIndex, criteria.PageSize);
            }
        }

        #endregion

        public User SearchByUserName(string userName)
        {
            using (var context = GetContext())
            {
                return context.Users.Include("Roles").FirstOrDefault(e => e.UserName == userName);
            }
        }
    }
}
